var AV = require('leanengine');
var async = require('async');

var UserCoupon = AV.Object.extend('UserCoupon');
var Coupons = AV.Object.extend('Coupons');
var ActivitySignDayGive = AV.Object.extend('ActivitySignDayGive');

module.exports = {

    //返还优惠券领取
    returnCoupons:function(){
        var promise = new AV.Promise();
        async.waterfall([
            //判断是否存在该优惠码
            function(callback){
                query = new AV.Query(ActivitySignDayGive);
                query.equalTo("RuleDays",'D30');
                query.equalTo("GiveMold",0);
                //query.equalTo("GiveTime",null);
                query.first().then(function(res){
                    if(res){
                        if(res){
                            callback(null,res);

                        }else{
                            callback({code:9001,msg:"无数据"});
                        }
                    }else{
                        callback({code:9001,msg:"bug1"});
                    }
                })
            },
            //领取优惠券
            function(res,callback){

                res.set("GiveMold",1);
                res.set("GiveTime",new Date());
                res.save();

                var takeCoupon = new UserCoupon();
                var coupon = {
                    "receiveEndPeriod": "1451528299000",
                    "batchNo": "签到优惠券现金10圆批次",
                    "receiveCondition": "",
                    "par": "10",
                    "receiveStartPeriod": "1446257899000",
                    "useCondition": "",
                    "consume": "0",
                    "syncStatus": 0,
                    "type": "1",
                    "cnt": "9999",
                    "status": "1",
                    "validityStartPeriod": "1446257899000",
                    "fileurl": "http://7xj380.com1.z0.glb.clouddn.com/2015-10-31_563424f69c29f.png",
                    "reduce": "0",
                    "validityEndPeriod": "1451528299000"
                };

                console.log('=================');
                console.log(res.get("Uid"));

                var newCoupon={'uid':res.get("Uid"),'cid':"签到优惠券现金10圆批次",'uphone':"",'uname':"",'validityEndPeriod':"1447084799000",'used':0,'status':1,GiveTime:new Date(),coupon:coupon};
                takeCoupon.save(newCoupon).then(function(res){
                    callback(null,{code:0});
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    }
};
